import { useState } from 'react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { 
  UserIcon, 
  CameraIcon, 
  PencilIcon, 
  HeartIcon,
  CalendarDaysIcon,
  EnvelopeIcon,
  PhoneIcon,
  KeyIcon,
  EyeIcon,
  EyeSlashIcon
} from '@heroicons/react/24/outline'
import { useAuthStore } from '@/stores/authStore'
import { toast } from 'react-hot-toast'
import userApi from '@/services/userApi'

const profileSchema = z.object({
  displayName: z.string().min(1, '显示名称不能为空').max(50, '显示名称最多50位字符'),
  bio: z.string().max(200, '个人简介最多200位字符').optional(),
  phone: z.string().optional(),
  birthday: z.string().optional(),
})

const passwordSchema = z.object({
  currentPassword: z.string().min(1, '当前密码不能为空'),
  newPassword: z.string().min(6, '新密码至少6位').max(50, '新密码最多50位'),
  confirmPassword: z.string().min(6, '确认密码至少6位').max(50, '确认密码最多50位'),
}).refine((data) => data.newPassword === data.confirmPassword, {
  message: "两次输入的密码不一致",
  path: ["confirmPassword"],
})

type ProfileFormData = z.infer<typeof profileSchema>
type PasswordFormData = z.infer<typeof passwordSchema>

const ProfilePage = () => {
  const { user, updateUser } = useAuthStore()
  const [isEditing, setIsEditing] = useState(false)
  const [isUploading, setIsUploading] = useState(false)
  const [bindingUsername, setBindingUsername] = useState('')
  const [isBinding, setIsBinding] = useState(false)
  const [showPasswordForm, setShowPasswordForm] = useState(false)
  const [showPasswords, setShowPasswords] = useState({
    current: false,
    new: false,
    confirm: false
  })

  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
    reset,
  } = useForm<ProfileFormData>({
    resolver: zodResolver(profileSchema),
    defaultValues: {
      displayName: user?.displayName || '',
      bio: user?.bio || '',
      phone: user?.phone || '',
      birthday: user?.birthday ? new Date(user.birthday).toISOString().split('T')[0] : '',
    },
  })

  const {
    register: registerPassword,
    handleSubmit: handleSubmitPassword,
    formState: { errors: passwordErrors, isSubmitting: isPasswordSubmitting },
    reset: resetPassword,
  } = useForm<PasswordFormData>({
    resolver: zodResolver(passwordSchema),
  })

  const onSubmit = async (data: ProfileFormData) => {
    try {
      await updateUser({
        displayName: data.displayName,
        bio: data.bio,
        phone: data.phone,
        birthday: data.birthday ? new Date(data.birthday) : undefined,
      })
      toast.success('个人资料更新成功！')
      setIsEditing(false)
    } catch (error: any) {
      toast.error(error.message || '更新失败，请重试')
    }
  }

  const handleCancel = () => {
    reset()
    resetPassword()
    setIsEditing(false)
    setShowPasswordForm(false)
    setShowPasswords({ current: false, new: false, confirm: false })
  }

  const onSubmitPassword = async (data: PasswordFormData) => {
    try {
      await userApi.changePassword({
        currentPassword: data.currentPassword,
        newPassword: data.newPassword
      })
      toast.success('密码修改成功')
      setShowPasswordForm(false)
      resetPassword()
      setShowPasswords({ current: false, new: false, confirm: false })
    } catch (error: any) {
      toast.error(error?.response?.data?.message || '密码修改失败')
    }
  }

  const handleAvatarUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (!file) return

    // 检查文件类型
    if (!file.type.startsWith('image/')) {
      toast.error('请选择图片文件')
      return
    }

    // 检查文件大小 (5MB)
    if (file.size > 5 * 1024 * 1024) {
      toast.error('图片大小不能超过5MB')
      return
    }

    setIsUploading(true)
    try {
      // 调用头像上传API
      const response = await userApi.uploadAvatar(file)
      
      // 更新本地用户信息
      await updateUser({ avatar: response.data.avatar })
      
      toast.success('头像上传成功！')
    } catch (error: any) {
      toast.error(error?.response?.data?.message || error.message || '头像上传失败')
    } finally {
      setIsUploading(false)
    }
  }

  const formatDate = (date: Date | string) => {
    const d = new Date(date)
    return d.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    })
  }

  const calculateAge = (birthday: Date | string) => {
    const today = new Date()
    const birth = new Date(birthday)
    let age = today.getFullYear() - birth.getFullYear()
    const monthDiff = today.getMonth() - birth.getMonth()
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
      age--
    }
    return age
  }

  if (!user) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <UserIcon className="h-12 w-12 text-gray-400 mx-auto mb-4" />
          <p className="text-gray-600">加载中...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* 页面头部 */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">个人资料</h1>
          <p className="text-gray-600 mt-1">
            管理你的个人信息 👤
          </p>
          <div className="mt-2">
            {((user as any)?.partnerId) ? (
              <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-50 text-green-700">
                已绑定 @{(user as any)?.partner?.username || '对方'}
              </span>
            ) : (
              <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-600">
                未绑定
              </span>
            )}
          </div>
        </div>
        {!isEditing && (
          <button
            onClick={() => setIsEditing(true)}
            className="btn-primary flex items-center gap-2"
          >
            <PencilIcon className="h-5 w-5" />
            编辑资料
          </button>
        )}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* 左侧：头像和基本信息 */}
        <div className="lg:col-span-1">
          <div className="card p-6 text-center">
            {/* 头像 */}
            <div className="relative inline-block mb-4">
              <div className="w-32 h-32 mx-auto">
                {user.avatar ? (
                  <img
                    src={user.avatar}
                    alt={user.displayName || user.username}
                    className="w-full h-full rounded-full object-cover"
                  />
                ) : (
                  <div className="w-full h-full rounded-full bg-primary-500 flex items-center justify-center text-white text-4xl font-bold">
                    {(user.displayName?.charAt(0) || user.username?.charAt(0) || 'U').toUpperCase()}
                  </div>
                )}
              </div>
              
              {/* 上传按钮 */}
              <label className="absolute bottom-0 right-0 bg-white rounded-full p-2 shadow-lg cursor-pointer hover:bg-gray-50 transition-colors">
                <CameraIcon className="h-5 w-5 text-gray-600" />
                <input
                  type="file"
                  accept="image/*"
                  onChange={handleAvatarUpload}
                  className="hidden"
                  disabled={isUploading}
                />
              </label>
              
              {isUploading && (
                <div className="absolute inset-0 bg-black/50 rounded-full flex items-center justify-center">
                  <div className="w-6 h-6 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                </div>
              )}
            </div>
            
            <h2 className="text-xl font-bold text-gray-900 mb-1">
              {user.displayName || user.username}
            </h2>
            <p className="text-gray-600 mb-4">@{user.username}</p>
            
            {user.bio && (
              <p className="text-sm text-gray-700 mb-4">{user.bio}</p>
            )}
            
            <div className="space-y-2 text-sm text-gray-600">
              <div className="flex items-center justify-center gap-2">
                <EnvelopeIcon className="h-4 w-4" />
                <span>{user.email}</span>
              </div>
              
              {user.phone && (
                <div className="flex items-center justify-center gap-2">
                  <PhoneIcon className="h-4 w-4" />
                  <span>{user.phone}</span>
                </div>
              )}
              
              {user.birthday && (
                <div className="flex items-center justify-center gap-2">
                  <CalendarDaysIcon className="h-4 w-4" />
                  <span>{formatDate(user.birthday)} ({calculateAge(user.birthday)}岁)</span>
                </div>
              )}
              
              <div className="flex items-center justify-center gap-2">
                <HeartIcon className="h-4 w-4" />
                <span>加入于 {formatDate(user.createdAt)}</span>
              </div>
            </div>
          </div>
        </div>

        {/* 右侧：绑定关系 + 详细信息 */}
        <div className="lg:col-span-2 space-y-6">
          {/* 绑定关系卡片 */}
          <div className="card p-6">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">绑定关系</h3>
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-600">当前绑定对象</p>
                  <p className="text-gray-900 font-medium">
                    {
                      ((user as any)?.partner?.username) 
                        ? `${(user as any)?.partner?.displayName || (user as any)?.partner?.username} (@${(user as any)?.partner?.username})`
                        : '暂无绑定'
                    }
                  </p>
                </div>
                {((user as any)?.partnerId) && (
                  <button
                    disabled={isBinding}
                    onClick={async () => {
                      try {
                        setIsBinding(true)
                        await userApi.unbindPartner()
                        // 同步刷新本地用户信息
                        const me = await userApi.getMe()
                        // 使用全局store的updateUser合并关键字段
                        useAuthStore.getState().updateUser({
                          partnerId: me.partnerId as any,
                          // @ts-ignore 允许保存partner信息到user对象，避免类型限制
                          partner: me.partner as any,
                        } as any)
                        toast.success('已解除绑定')
                      } catch (e:any) {
                        toast.error(e?.response?.data?.message || '解除绑定失败')
                      } finally {
                        setIsBinding(false)
                      }
                    }}
                    className="btn-secondary"
                  >
                    {isBinding ? '处理中...' : '解除绑定'}
                  </button>
                )}
              </div>

              <div className="grid grid-cols-1 md:grid-cols-[1fr_auto] gap-3">
                <input
                  type="text"
                  value={bindingUsername}
                  onChange={(e) => setBindingUsername(e.target.value)}
                  placeholder="输入要绑定的用户名"
                  className="input-field"
                />
                <button
                  disabled={!bindingUsername || isBinding}
                  onClick={async () => {
                    if (!bindingUsername) return
                    try {
                      setIsBinding(true)
                      await userApi.bindPartner(bindingUsername.trim())
                      const me = await userApi.getMe()
                      useAuthStore.getState().updateUser({
                        partnerId: me.partnerId as any,
                        // @ts-ignore
                        partner: me.partner as any,
                      } as any)
                      setBindingUsername('')
                      toast.success('绑定成功')
                    } catch (e:any) {
                      toast.error(e?.response?.data?.message || '绑定失败')
                    } finally {
                      setIsBinding(false)
                    }
                  }}
                  className="btn-primary"
                >
                  {isBinding ? '处理中...' : '绑定'}
                </button>
              </div>

              <p className="text-xs text-gray-500">
                说明：绑定后双方将共享数据与存储（当前支持便签，后续支持相册）。如需更换绑定对象，请先解除再绑定。
              </p>
            </div>
          </div>

          <div className="card p-6">
            <h3 className="text-lg font-semibold text-gray-900 mb-6">详细信息</h3>
            
            {showPasswordForm ? (
              <form onSubmit={handleSubmitPassword(onSubmitPassword)} className="space-y-6">
                <div className="text-center mb-6">
                  <KeyIcon className="h-8 w-8 text-gray-400 mx-auto mb-2" />
                  <p className="text-sm text-gray-600">修改登录密码 🔐</p>
                </div>

                {/* 当前密码 */}
                <div>
                  <label htmlFor="currentPassword" className="block text-sm font-medium text-gray-700 mb-2">
                    当前密码
                  </label>
                  <div className="relative">
                    <input
                      {...registerPassword('currentPassword')}
                      type={showPasswords.current ? 'text' : 'password'}
                      id="currentPassword"
                      className={`input-field pr-12 ${passwordErrors.currentPassword ? 'border-red-300 focus:border-red-500 focus:ring-red-500' : ''}`}
                      placeholder="请输入当前密码"
                    />
                    <button
                      type="button"
                      className="absolute inset-y-0 right-0 pr-4 flex items-center hover:text-primary-600 transition-colors"
                      onClick={() => setShowPasswords(prev => ({ ...prev, current: !prev.current }))}
                    >
                      {showPasswords.current ? (
                        <EyeSlashIcon className="h-5 w-5" />
                      ) : (
                        <EyeIcon className="h-5 w-5" />
                      )}
                    </button>
                  </div>
                  {passwordErrors.currentPassword && (
                    <p className="mt-1 text-sm text-red-600">{passwordErrors.currentPassword.message}</p>
                  )}
                </div>

                {/* 新密码 */}
                <div>
                  <label htmlFor="newPassword" className="block text-sm font-medium text-gray-700 mb-2">
                    新密码
                  </label>
                  <div className="relative">
                    <input
                      {...registerPassword('newPassword')}
                      type={showPasswords.new ? 'text' : 'password'}
                      id="newPassword"
                      className={`input-field pr-12 ${passwordErrors.newPassword ? 'border-red-300 focus:border-red-500 focus:ring-red-500' : ''}`}
                      placeholder="请输入新密码（至少6位）"
                    />
                    <button
                      type="button"
                      className="absolute inset-y-0 right-0 pr-4 flex items-center hover:text-primary-600 transition-colors"
                      onClick={() => setShowPasswords(prev => ({ ...prev, new: !prev.new }))}
                    >
                      {showPasswords.new ? (
                        <EyeSlashIcon className="h-5 w-5" />
                      ) : (
                        <EyeIcon className="h-5 w-5" />
                      )}
                    </button>
                  </div>
                  {passwordErrors.newPassword && (
                    <p className="mt-1 text-sm text-red-600">{passwordErrors.newPassword.message}</p>
                  )}
                </div>

                {/* 确认密码 */}
                <div>
                  <label htmlFor="confirmPassword" className="block text-sm font-medium text-gray-700 mb-2">
                    确认新密码
                  </label>
                  <div className="relative">
                    <input
                      {...registerPassword('confirmPassword')}
                      type={showPasswords.confirm ? 'text' : 'password'}
                      id="confirmPassword"
                      className={`input-field pr-12 ${passwordErrors.confirmPassword ? 'border-red-300 focus:border-red-500 focus:ring-red-500' : ''}`}
                      placeholder="请再次输入新密码"
                    />
                    <button
                      type="button"
                      className="absolute inset-y-0 right-0 pr-4 flex items-center hover:text-primary-600 transition-colors"
                      onClick={() => setShowPasswords(prev => ({ ...prev, confirm: !prev.confirm }))}
                    >
                      {showPasswords.confirm ? (
                        <EyeSlashIcon className="h-5 w-5" />
                      ) : (
                        <EyeIcon className="h-5 w-5" />
                      )}
                    </button>
                  </div>
                  {passwordErrors.confirmPassword && (
                    <p className="mt-1 text-sm text-red-600">{passwordErrors.confirmPassword.message}</p>
                  )}
                </div>

                {/* 按钮组 */}
                <div className="flex space-x-4">
                  <button
                    type="submit"
                    disabled={isPasswordSubmitting}
                    className="btn-primary"
                  >
                    {isPasswordSubmitting ? '修改中...' : '修改密码'}
                  </button>
                  <button
                    type="button"
                    onClick={() => setShowPasswordForm(false)}
                    className="btn-secondary"
                  >
                    取消
                  </button>
                </div>
              </form>
            ) : isEditing ? (
              <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
                {/* 显示名称 */}
                <div>
                  <label htmlFor="displayName" className="block text-sm font-medium text-gray-700 mb-2">
                    显示名称
                  </label>
                  <input
                    {...register('displayName')}
                    type="text"
                    id="displayName"
                    className={`input-field ${errors.displayName ? 'border-red-300 focus:border-red-500 focus:ring-red-500' : ''}`}
                    placeholder="请输入显示名称"
                  />
                  {errors.displayName && (
                    <p className="mt-1 text-sm text-red-600">{errors.displayName.message}</p>
                  )}
                </div>

                {/* 个人简介 */}
                <div>
                  <label htmlFor="bio" className="block text-sm font-medium text-gray-700 mb-2">
                    个人简介
                  </label>
                  <textarea
                    {...register('bio')}
                    id="bio"
                    rows={3}
                    className={`input-field ${errors.bio ? 'border-red-300 focus:border-red-500 focus:ring-red-500' : ''}`}
                    placeholder="介绍一下自己吧..."
                  />
                  {errors.bio && (
                    <p className="mt-1 text-sm text-red-600">{errors.bio.message}</p>
                  )}
                </div>

                {/* 手机号 */}
                <div>
                  <label htmlFor="phone" className="block text-sm font-medium text-gray-700 mb-2">
                    手机号
                  </label>
                  <input
                    {...register('phone')}
                    type="tel"
                    id="phone"
                    className={`input-field ${errors.phone ? 'border-red-300 focus:border-red-500 focus:ring-red-500' : ''}`}
                    placeholder="请输入手机号"
                  />
                  {errors.phone && (
                    <p className="mt-1 text-sm text-red-600">{errors.phone.message}</p>
                  )}
                </div>

                {/* 生日 */}
                <div>
                  <label htmlFor="birthday" className="block text-sm font-medium text-gray-700 mb-2">
                    生日
                  </label>
                  <input
                    {...register('birthday')}
                    type="date"
                    id="birthday"
                    className={`input-field ${errors.birthday ? 'border-red-300 focus:border-red-500 focus:ring-red-500' : ''}`}
                  />
                  {errors.birthday && (
                    <p className="mt-1 text-sm text-red-600">{errors.birthday.message}</p>
                  )}
                </div>

                {/* 按钮组 */}
                <div className="flex space-x-4">
                  <button
                    type="submit"
                    disabled={isSubmitting}
                    className="btn-primary"
                  >
                    {isSubmitting ? '保存中...' : '保存更改'}
                  </button>
                  <button
                    type="button"
                    onClick={handleCancel}
                    className="btn-secondary"
                  >
                    取消
                  </button>
                </div>
              </form>
            ) : (
              <div className="space-y-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    显示名称
                  </label>
                  <p className="text-gray-900">{user.displayName || '未设置'}</p>
                </div>
                
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    个人简介
                  </label>
                  <p className="text-gray-900">{user.bio || '这个人很懒，什么都没写...'}</p>
                </div>
                
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    邮箱地址
                  </label>
                  <p className="text-gray-900">{user.email}</p>
                </div>
                
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    手机号
                  </label>
                  <p className="text-gray-900">{user.phone || '未设置'}</p>
                </div>
                
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    生日
                  </label>
                  <p className="text-gray-900">
                    {user.birthday ? `${formatDate(user.birthday)} (${calculateAge(user.birthday)}岁)` : '未设置'}
                  </p>
                </div>
                
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    注册时间
                  </label>
                  <p className="text-gray-900">{formatDate(user.createdAt)}</p>
                </div>

                {/* 密码修改按钮 */}
                <div className="pt-4 border-t border-gray-200">
                  <button
                    onClick={() => setShowPasswordForm(true)}
                    className="btn-secondary flex items-center gap-2"
                  >
                    <KeyIcon className="h-4 w-4" />
                    修改密码
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}

export default ProfilePage